<template>
  <div>
    <hsa-adaptive-container>
      <hsa-adaptive-pane>
        <hsa-title-pane>
          <hsa-title-pane-item title="查询条件">
            <t-query-condition
              :opts="opts"
              ref="myQuery"
              @submit="conditionEnter"
              @handleEvent="handleEvent"
              isExpansion
            />
          </hsa-title-pane-item>
        </hsa-title-pane>
      </hsa-adaptive-pane>
      <hsa-adaptive-pane>
        <hsa-title-pane>
          <hsa-title-pane-item title="报表信息">
            <template #toolbar>
              <div class="right-box">
                <el-button type="primary" @click="addReport">新建</el-button>
                <div class="change-box">
                  <span
                    :class="{ active: state.active == 1 }"
                    @click="changeType(1)"
                    >平铺</span
                  >
                  <span
                    :class="{ active: state.active == 2 }"
                    @click="changeType(2)"
                    >文件夹</span
                  >
                </div>
              </div>
            </template>
            <div v-if="state.active == 1">
              <t-table
                :table="table"
                :columns="table.columns"
                :tableLoading="tableLoading"
                @page-change="pageChange"
                @size-change="sizeChange"
                isPaginationCumulative
              />
              <!-- <template #operator="{ scope }">
                  <el-button color="#626aef" icon="Edit" @click="viewDetail(scope.row)">查看</el-button>
                  <el-button type="danger" icon="Search" @click="edit(scope.row)">编辑</el-button>
                  <el-button size="default" type="primary" @click="nullify(scope.row)">作废</el-button>
                </template> -->
              <!-- </t-table> -->
            </div>
            <div v-else>
              <div class="list-box" v-for="(it, i) in state.tableData" :key="i">
                <div class="list-title">
                  <img src="./images/fileBox.png" alt="" srcset="" />
                  <div>{{ it.sourceName || "" }}</div>
                </div>
                <div class="list-main">
                  <div
                    class="list-item"
                    v-for="(its, ix) in it.children"
                    :key="ix"
                  >
                    <div class="item-header">
                      <div>{{ its.name || "" }}</div>
                      <!-- <div>
                        <div>行 XX字段</div>
                        <div>列 XX字段</div>
                      </div> -->
                      <div>
                        <span>{{ it.sourceName || "" }}</span>
                        <span>{{ its.createTime || "" }}</span>
                      </div>
                    </div>
                    <div class="item-footer">
                      <div @click="viewDetail(its)">权限</div>
                      <div @click="edit(its)">编辑</div>
                      <div @click="del(its)">删除</div>
                    </div>
                  </div>
                </div>
              </div>

              <div class="pagination-box">
                <el-pagination
                  v-model:current-page="paginationFrom.pageNumber"
                  v-model:page-size="paginationFrom.pageSize"
                  :page-sizes="[10, 20, 50, 100]"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="paginationFrom.total"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                />
              </div>
            </div>
          </hsa-title-pane-item>
        </hsa-title-pane>
      </hsa-adaptive-pane>
    </hsa-adaptive-container>
    <analysis-report-share ref="myShare" @successHand="getData" />
  </div>
</template>
<script setup lang="ts">
import analysisReportShare from "./model/analysis-report-share.vue";
// import hsaAdaptiveContainer from '@/components/hsa/adaptive/container.vue'
// import hsaAdaptivePane from '@/components/hsa/adaptive/pane.vue'
// import HasTitle from "@/components/hsa/title-box.vue";
import { onMounted, computed, reactive, toRefs, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from 'vue-router'
import apiAxios from "@/api/SelfAnalysis/analysis-report-manage";
import { PAth } from "@/api/SelfAnalysis/query";
const router = useRouter()
const queryFrom = ref(PAth());
const tableLoading = ref<boolean>(false)
const addReport = () => {
  router.push('/self-analysis/report-config')
};
const changeType = (num: number) => {
  state.active = num;
  paginationFrom.pageNumber = 1;
  myQuery.value.resetHandle();
};
const myQuery = ref(null);
const myShare = ref(null);

const viewDetail = (val: any) => {
  console.log("viewDetail", val);
  myShare.value.open(val.id);
};
const edit = (val: any) => {
  router.push({path:'/self-analysis/report-config',query:{id:val.id}})
};
const del = (val: any) => {
  ElMessageBox.confirm(`确认删除？`, "提示").then(async () => {
    try {
      let res = await apiAxios.dataDel(val.id);
      if (res) {
        ElMessage({
          type: "success",
          message: "删除成功!",
        });
        getData();
      }
    } catch (err) {
      ElMessage({
        message: "删除失败",
        type: "error",
        showClose: false,
      });
    }
  });
};
const paginationFrom = {
  pageNumber: 1,
  pageSize: 10,
  total: 0,
};
const handleSizeChange = (val: number) => {
  paginationFrom.pageNumber = 1;
  paginationFrom.pageSize = val;
  getData();
};
const handleCurrentChange = (val: number) => {
  paginationFrom.pageNumber = val;
  getData();
};
const table = ref<TableTypes.Table>({
  firstColumn: { type: "index", width: 80, fixed: true },
  total: paginationFrom.total,
  currentPage: paginationFrom.pageNumber,
  pageSize: paginationFrom.pageSize,
  layout: "total,sizes, slot, prev, pager, next, jumper",
  prevText: "上一页",
  nextText: "下一页",
  // 接口返回数据
  data: [],
  // 表头数据
  columns: [
    { prop: "name", label: "报表名称" },
    { prop: "createBy", label: "创建人" },
    { prop: "createTime", label: "创建时间" },
    {
      prop: "source",
      label: "所属团队",
      render: (text, record) => {
        let val = "";
        switch (record.source) {
          case "0":
            val = "我创建的";
            break;
          case "1":
            val = "我团队创建的";
            break;
          case "2":
            val = "分享给我的";
            break;
        }
        return val;
      },
    },
  ],
  // 表格内操作列
  operator: [
    {
      text: "权限",
      fun: viewDetail,
      //   noshow: [{ key: "status", val: ["1"] }]
    },
    {
      text: "编辑",
      fun: edit,
    },
    {
      text: "删除",
      fun: del,
      bind: {
        type: "danger",
        text: true,
      },
    },
  ],
  // 操作列样式
  operatorConfig: {
    // fixed: "right", // 固定列表右边（left则固定在左边）
    width: 280,
    label: "操作",
  },
});
let state = reactive({
  active: 1,
  tableData: [],
  listTypeInfo: {
    sexList: [
      {
        label: "是",
        key: "1",
      },
      {
        label: "否",
        key: "0",
      },
    ],
  },
});
const opts = computed(() => {
  return {
    name: {
      label: "报表名称",
      comp: "el-input",
    },
    isMe: {
      label: "自己创建",
      comp: "el-select",
      changeEvent: "change",
      type: "select-arr",
      list: "sexList",
      listTypeInfo: state.listTypeInfo,
    },
  };
});

onMounted(() => {
  getData();
});
const getData = async () => {
  tableLoading.value = true
  let res;
  let pageObj = JSON.parse(JSON.stringify(paginationFrom));
  delete pageObj.total;
  let obj = {
    ...queryFrom.value,
    ...pageObj,
  };
  res = await apiAxios.getQueryList(obj);
  tableLoading.value = false
  if (res) {
    paginationFrom.total = res.total;
    table.value.total = res.total;
    if (state.active == 2) {
      let arr = res.records.reduce((result, item) => {
        let index = result.findIndex((it) => it.source == item.source);
        if (index == -1) {
          let val = "";
          switch (item.source) {
            case "0":
              val = "我创建的";
              break;
            case "1":
              val = "我团队创建的";
              break;
            case "2":
              val = "分享给我的";
              break;
          }
          result.push({
            sourceName: val,
            source: item.source,
            children: [item],
          });
        } else {
          result[index].children.push(item);
        }
        return result;
      }, []);
      console.log(arr, "arr");
      state.tableData = arr;
    } else {
      table.value.data = res.records;
    }
  }
};
// 查询条件change事件
const handleEvent = (type, val) => {
  switch (type) {
    case "date":
      console.log("获取event==date的数据", val);
      break;
  }
};
// 点击查询按钮
const conditionEnter = (data: any) => {
  for (const key in data) {
    if (data[key] == null || data[key] == "") {
      data[key] = undefined;
    }
  }
  queryFrom.value = data;
  getData();
};
// 选择当前页码
const pageChange = (page: number) => {
  table.value.currentPage = page;
  paginationFrom.pageNumber = page;
  getData();
};
// 选择当页条数
const sizeChange = (size: number) => {
  table.value.currentPage = 1;
  table.value.pageSize = size;
  paginationFrom.pageNumber = 1;
  paginationFrom.pageSize = size;
  getData();
};
</script>

<style lang="scss" scoped>
.right-box {
  display: flex;
  align-items: center;
  .change-box {
    margin-left: 30px;
    span {
      display: inline-block;
      padding: 4px 15px;
      cursor: pointer;
      border: 1px solid #ccc;
      box-sizing: border-box;
      transform: skew(-20deg);
      &.active {
        background-color: #d7d7d7;
      }
    }
  }
}
$rowNum: 3;
.list-box {
  width: 100%;
  margin-bottom: 30px;
  .list-title {
    margin-bottom: 20px;
    display: flex;
    align-items: flex-end;
    img {
      width: 34px;
      height: 28px;
      margin-right: 10px;
      object-fit: contain;
    }
  }
  .list-main {
    width: 100%;
    display: flex;
    gap: 20px;
    flex-wrap: wrap;
    padding-left: 44px;
    box-sizing: border-box;
    .list-item {
      width: calc((100% - calc(20px * ($rowNum - 1))) / $rowNum);
      border: 1px solid #ccc;
      box-sizing: border-box;
      .item-header {
        width: 100%;
        padding: 20px;
        box-sizing: border-box;
        > div {
          &:not(:first-child) {
            margin-top: 20px;
            padding-left: 20px;
            box-sizing: border-box;
          }
          &:first-child {
            font-size: 20px;
            font-weight: bold;
          }
          &:last-child {
            width: 100%;
            display: flex;
            justify-content: space-between;
          }
        }
      }
      .item-footer {
        width: 100%;
        display: flex;
        > div {
          width: calc(100% / 3);
          height: 40px;
          line-height: 40px;
          text-align: center;
          cursor: pointer;
          border: 1px solid #ccc;
          box-sizing: border-box;
        }
      }
    }
  }
}
.pagination-box {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  margin-top: 30px;
}
</style>
